package com.lam.schedule.controller;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.write.handler.WriteHandler;
import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.Result;
import com.lam.common.components.dict.annotation.DictAutoTransfer;
import com.lam.common.components.easyexcel.export.DownloadUtil;
import com.lam.common.components.easyexcel.imp.ImportUtil;
import com.lam.common.components.redis.RedisUtil;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.IpUtils;
import com.lam.common.utils.StringUtils;
import com.lam.common.validate.ValidateUtil;
import com.lam.common.validate.group.Add;
import com.lam.common.validate.group.Update;
import com.lam.common.validate.model.ValidOperType;
import com.lam.framework.annotation.ParamInject;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.framework.operLog.enums.LogSave;
import com.lam.schedule.common.constant.ScheduleConstant;
import com.lam.schedule.common.scheduler.model.TargetClass;
import com.lam.schedule.common.scheduler.util.InvokeUtils;
import com.lam.schedule.entity.QrtzJobSchedilerState;
import com.lam.schedule.entity.ScheduleJob;
import com.lam.schedule.entity.imp.ScheduleJobImp;
import com.lam.schedule.listener.UploadScheduleJobListener;
import com.lam.schedule.param.ScheduleJobParam;
import com.lam.schedule.service.ScheduleJobService;

/**
 * 定时调度任务Controller
 * 
 * @author admin
 * @date 2022-06-24
 */
@Log(title = "定时调度任务")
@ParamInject
@RestController
@RequestMapping("/${adminPath}/sched/job")
public class ScheduleJobController extends BaseController {

    @Autowired
    private ScheduleJobService scheduleJobService;

    /**
     * 查询定时调度任务列表
     */
    @Log(oper="分页查询")
    @DictAutoTransfer
    @PreAuthorize("@ss.hasPm('sched:job:list')")
    @GetMapping("/list")
    public Result list(ScheduleJobParam param) {
    
        startPage();
        param.setWithscheduleStatus(true);
        List<ScheduleJob> list = scheduleJobService.selectList(param);
        return Result.ok(getTableData(list));
    }
    
    @Log(oper="节点分布查询")
    @DictAutoTransfer
    @PreAuthorize("@ss.hasPm('sched:job:nodeDetail')")
    @GetMapping("/nodeDetail/{id}")
    public Result nodeDetailList(@PathVariable("id") String id) {
    	
        List<QrtzJobSchedilerState> list = scheduleJobService.nodeDetailList(id);
        return Result.ok(getTableData(list));
    }
    
    /**
     * 导出定时调度任务列表
     */
    @PreAuthorize("@ss.hasPm('sched:job:export')")
    @Log(businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public Result export(ScheduleJobParam param) {
    
    	withOrderBy();
        List<ScheduleJob> list = scheduleJobService.selectList(param);
        return Result.ok(DownloadUtil.exportExcel("定时调度任务导出", list, ScheduleJob.class));
    }
    
    @Log(businessType = BusinessType.EXPORT, oper = "下载导入模板")
    @PreAuthorize("@ss.hasPm('sched:job:import')")
    @GetMapping("/downloadTemplate")
    public Result downloadTemplate() {
        WriteHandler headRowCommentWriteHandler = ImportUtil.getHeadRowCommentWriteHandler(ScheduleJobImp.class, ScheduleJob.class, Add.class);
        WriteHandler dropDownWriteHandler = ImportUtil.getDropDownWriteHandler(ScheduleJobImp.class, Add.class);
        return Result.ok(DownloadUtil.exportExcel("定时调度导入模板", Collections.emptyList(), ScheduleJobImp.class, 
            headRowCommentWriteHandler, dropDownWriteHandler));
    }
    
    @Log(businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPm('sched:job:import')")
    @PostMapping("/importData")
    public Result importData(MultipartFile file, boolean updateSupport) {
        
        logger.info("定时调度数据导入, 开始接收文件数据...");
        UploadScheduleJobListener readListener = new UploadScheduleJobListener(scheduleJobService);
        readListener.setUpdateSupport(updateSupport);
        ImportUtil.importData("定时调度", file, readListener);
        Map<String, Object> data = readListener.getOperResult();
        data.put("originalFilename", file.getOriginalFilename());
        return Result.ok(data);
    }

    /**
     * 获取定时调度任务详细信息
     */
    @DictAutoTransfer
    @Log(oper="根据ID查询")
    @PreAuthorize("@ss.hasPm('sched:job:query')")
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable("id") String id) {
    
        return Result.ok(scheduleJobService.selectById(id));
    }
    
    /**
     * 查询全部的任务执行目标类
     */
    @Log(oper="查询执行目标类")
    @PreAuthorize("@ss.hasPm('sched:job:listTargetClass')")
    @GetMapping("/listTargetClass")
    public Result listTargetClass(ScheduleJob scheduleJob) {
    
    	List<TargetClass> list = CollectionUtil.cast(RedisUtil.get(ScheduleConstant.TARGET_CLASS_KEY + IpUtils.getHostIp()));
        return Result.ok(list);
    }

    /**
     * 新增定时调度任务
     */
    @PreAuthorize("@ss.hasPm('sched:job:add')")
    @Log(businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated(Add.class) @RequestBody ScheduleJob scheduleJob) {
    	
    	ValidateUtil.validUnique(scheduleJob, ValidOperType.ADD, ScheduleConstant.UNIQUE_JOB_NAME, "任务名称已存在！");
    	String checkRes = InvokeUtils.checkJob(scheduleJob);
		if(StringUtils.isNotBlank(checkRes)){
			logger.error(checkRes);
			return Result.fail(checkRes);
		}
        return toAjax(scheduleJobService.insert(scheduleJob));
    }

    /**
     * 修改定时调度任务
     */
    @PreAuthorize("@ss.hasPm('sched:job:edit')")
    @Log(businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@Validated(Update.class) @RequestBody ScheduleJob scheduleJob) {
    	
    	ValidateUtil.validUnique(scheduleJob, ValidOperType.UPDATE, ScheduleConstant.UNIQUE_JOB_NAME, "任务名称已存在！");
    	
    	String checkRes = InvokeUtils.checkJob(scheduleJob);
		if(StringUtils.isNotBlank(checkRes)){
			logger.error(checkRes);
			return Result.fail(checkRes);
		}
        return toAjax(scheduleJobService.update(scheduleJob));
    }
    
    /**
     * 修改定时调度任务状态
     */
    @PreAuthorize("@ss.hasPm('sched:job:edit')")
    @Log(businessType = BusinessType.UPDATE, oper = "更改任务状态")
    @PostMapping("/editStatus")
    public Result editStatus(@RequestBody ScheduleJob scheduleJob) {
    	
    	ValidateUtil.validRequired(scheduleJob.getId(), "id不能为空");
    	ValidateUtil.validRequired(scheduleJob.getStatus(), "状态不能为空");
    	
        return toAjax(scheduleJobService.active(scheduleJob));
    }

    /**
     * 删除定时调度任务
     */
    @PreAuthorize("@ss.hasPm('sched:job:remove')")
    @Log(businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public Result remove(@PathVariable String id) {
    
        return toAjax(scheduleJobService.deleteById(id));
    }
    
    /**
     * 执行任务
     */
    @PreAuthorize("@ss.hasPm('sched:job:execute')")
    @Log(businessType = BusinessType.OTHER, logSave = LogSave.YES, oper = "执行调度任务")
    @PostMapping("execute/{id}")
    public Result execute(@PathVariable String id) {
    	
    	return toAjax(scheduleJobService.execute(id));
    }
}
